package com.photoeditor.demo.ui.widget.image.eraser;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.photoeditor.R;

/**
 * Created by Lai on 2018/1/4 0004.
 */

public class EraserBgView extends View {

    private Bitmap mTransparentBgBitmap;
    private RectF mContentRect;
    private Paint mBitmapPaint;

    public EraserBgView(Context context) {
        this(context, null);
    }

    public EraserBgView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public EraserBgView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mBitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        mContentRect = new RectF();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mTransparentBgBitmap != null && !mTransparentBgBitmap.isRecycled() && !mContentRect.isEmpty()) {
            canvas.drawBitmap(mTransparentBgBitmap, null, mContentRect, mBitmapPaint);
        }
    }

    public void createBgBitmap(RectF contentRect) {
        if (mTransparentBgBitmap != null && !mTransparentBgBitmap.isRecycled()) {
            mTransparentBgBitmap.recycle();
            mTransparentBgBitmap = null;
        }
        mContentRect.set(contentRect);
        int bgWidth = (int) mContentRect.width();
        int bgHeight = (int) mContentRect.height();
        mTransparentBgBitmap = Bitmap.createBitmap(bgWidth, bgHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(mTransparentBgBitmap);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_transparent_grid);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.FILL);
        paint.setShader(new BitmapShader(bitmap, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
        canvas.drawRect(0, 0, bgWidth, bgHeight, paint);
        invalidate();
    }

    public void updateContentRect(RectF rectF) {
        mContentRect.set(rectF);
        invalidate();
    }

    public Bitmap getTransparentBgBitmap() {
        return mTransparentBgBitmap;
    }

    public void reset() {
        setVisibility(GONE);
        if (mTransparentBgBitmap != null && !mTransparentBgBitmap.isRecycled()) {
            mTransparentBgBitmap.recycle();
            mTransparentBgBitmap = null;
        }
        mContentRect.setEmpty();
    }
}
